package com.h2cloud.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.Map;

/**
 * @PackageName: com.h2cloud.utils
 * @ClasssName: JWTUtil
 * @Author: h2cloud
 * @Date: 2021/3/10 12:32
 */
public class JWTUtil {
    private static String TOKEN = "woshinibaba";

    /**
     * 生成 token
     * @param map // 传入 payload
     * @return
     */
    public static String getToken(Map<String, String> map) {
        JWTCreator.Builder builder = JWT.create();
        map.forEach((k, v) -> {
            builder.withClaim(k, v);
        });

        Calendar instsance = Calendar.getInstance();
        instsance.add(Calendar.SECOND, 140000);
        builder.withExpiresAt(instsance.getTime());
        return builder.sign(Algorithm.HMAC256(TOKEN)).toString();
    }

    /**
     * 验证 token
     * @param token
     */
    public static void verify(String token){
        JWT.require(Algorithm.HMAC256(TOKEN)).build().verify(token);
    }

    /**
     * 获取 token 中的 payload
     * @param token
     * @return
     */
    public static DecodedJWT getToken(String token){
        return JWT.require(Algorithm.HMAC256(TOKEN)).build().verify(token);
    }

}
